﻿using System.IO;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using Newtonsoft.Json;
using ZilLion.Service.Crm.ModelBase.EntityBase.Config;
using ZilLion.Service.Crm.Unities.Config;

namespace ZilLion.Service.WebInfrastructure.Base
{
    public class GloabConfigLoader
    {
        private static string baseaddress;
        private static IGloabConfigHandler _gloabConfigHandler;
        public static ConfigGroup configs { get; set; }

        public static string GetConfigValue(string pkey, bool IsThrowException = true)
        {
            if (configs == null) return null;
            var item = configs.ConfigItems.FirstOrDefault(tr => tr.jkey == pkey);
            if (item == null && IsThrowException)
            {
                throw new System.Exception("配置不正确：key" + pkey);
            }
            return item?.jvalue;
        }

        public static string GetConfigTenPayV3ModelValue()
        {
            var items = configs.ConfigItems.Where(tr => tr.jkey.Contains("TenPayV3Model")).OrderBy(tr => tr.orderkey);
            StringBuilder sb = new StringBuilder();
            foreach (var item in items)
            {
                sb.Append(item.jvalue);
            }
            return sb.ToString();
        }

        private static FileSystemWatcher watcher;

        public static void SetBaseaddress(string configPath)
        {
            baseaddress = configPath;
        }

        public static void InitGloabConfigLoader(IGloabConfigHandler GloabConfigHandler, string configPath)
        {
            try
            {
                SetHandler(GloabConfigHandler);
                SetBaseaddress(configPath);
                SaveConfigGroup();
                LoadConfigGroup();
                LoadCheckConfigItems();
                LoadFileSystemWatcher();

            }
            catch (System.Exception ex)
            {
                //LogHelper.LogException(ex, "配置");
                throw ex;
            }
            if (!ZlConfig.HasRedis)
            {
                //fuleiming
                throw new System.Exception("ew");
            }
        }

        private static void SetHandler(IGloabConfigHandler GloabConfigHandler)
        {
            _gloabConfigHandler = GloabConfigHandler;
        }

        private static void LoadCheckConfigItems()
        {
            TaskFactory tf = new TaskFactory();
            Task task1 = tf.StartNew(CheckConfigItems);
        }

        public static object tmp = new object();

        private static void CheckConfigItems()
        {
            try
            {
                while (true)
                {
                    Thread.Sleep(20000);
                    int logsn2 = _gloabConfigHandler.CheckConfigItems();
                    if (logsn2 > configs.logsn)
                    {
                        configs.logsn = logsn2;
                        SaveConfigGroup();
                    }
                }
            }
            catch (System.Exception ex)
            {

            }
        }


        private static void SaveConfigGroup()
        {
            lock (tmp)
            {
                string Appid = (string)ConfigurationManager.AppSettings["Appid"];

                string configfilepath = string.Format("{0}/config.json", baseaddress);
                configs = _gloabConfigHandler.GetConfigItem(Appid);
                string config = JsonConvert.SerializeObject(configs, Formatting.Indented);
                if (!Directory.Exists(baseaddress))
                {
                    Directory.CreateDirectory(baseaddress);
                }
                using (TextWriter tw = new StreamWriter(configfilepath, false))
                {
                    tw.WriteLine(config);
                    tw.Flush();
                    tw.Close();
                }
            }
        }

        private static void LoadFileSystemWatcher()
        {
            watcher = new FileSystemWatcher(baseaddress);
            watcher.Filter = "*.json";   //设置监控文件的类型  
            watcher.EnableRaisingEvents = true;
            watcher.Changed += new FileSystemEventHandler(watcher_Changed);
        }

        static void watcher_Changed(object sender, FileSystemEventArgs e)
        {
            try
            {
                LoadConfigGroup();
                ZlConfig.IsnotifyDecrypt = true;
            }
            catch (IOException ex)
            {

            }
        }

        private static void LoadConfigGroup()
        {
            string configfilepath = string.Format("{0}/config.json", baseaddress);
            if (File.Exists(configfilepath))
            {
                using (TextReader tw = new StreamReader(configfilepath))
                {
                    string configjson = tw.ReadToEnd();
                    configs = JsonConvert.DeserializeObject<ConfigGroup>(configjson);
                }
                return;
            }
        }

        public static void ReaderConfigs(string path)
        {
            if (File.Exists(path))
            {
                using (TextReader tw = new StreamReader(path))
                {
                    string configjson = tw.ReadToEnd();
                    configs = JsonConvert.DeserializeObject<ConfigGroup>(configjson);
                }
                //return;
            }
        }
    }
}
